package com.ldl.listener;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

import com.ldl.service.CountService;
import com.ldl.service.impl.CountServiceImpl;

/**
 * @author Administrator
 * Author : L.D.L
 * E-mail : 1419485293@qq.com
 * Date : 2020年8月7日下午8:13:28
 */
@WebListener
public class CountListener implements HttpSessionListener,ServletContextListener{

	private int count = 0;
	private int online = 0;
	
	private ServletContext application;
	private CountService countService = new CountServiceImpl();
	
	@Override
	public void contextInitialized(ServletContextEvent sce) {
		//读取之前保存的访问数量
		count = countService.getCount();
		
		application = sce.getServletContext();
		application.setAttribute("count", count);
		application.setAttribute("online", online);
	}
	
	
	@Override
	public void sessionCreated(HttpSessionEvent se) {
		count ++;
		online ++;
		application.setAttribute("count", count);
		application.setAttribute("online", online);
//		se.getSession().getServletContext().setAttribute("count", count);
//		se.getSession().getServletContext().setAttribute("online", online);
	}
	
	@Override
	public void sessionDestroyed(HttpSessionEvent se) {
		online --;
//		se.getSession().getServletContext().setAttribute("online", online);
		application.setAttribute("online", online);
	}
	
	
	@Override
	public void contextDestroyed(ServletContextEvent sce) {
		// 保存现在访问的人数
		countService.saveCount(count);
	}

}
